package com.ruoyi.web.controller;

//import com.example.demo.Util.AliOssCloudUtil;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
public class FileUploadController {

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/file/upload")
    public String updateFileReturnPath(@RequestParam("MultipartFile")MultipartFile multipartFile) {
        //华北是zone1, [华东z0] [华南z2] [北美na0] [东南亚as0]
        try {
            com.qiniu.storage.Configuration configuration = new com.qiniu.storage.Configuration(Zone.zone1());//七牛云配置
            UploadManager uploadManager = new UploadManager(configuration);//七牛云上传管理
            Auth auth = Auth.create("84JdHw_WDk1kivlPJtkHv_lL6jRxm3G1jkRfWww_", "fjasRtIGIqqggSDEssoz0nGi06duZZUkjEoQTfrp");//需要传入key和secret
            String token = auth.uploadToken("yiyiyitestdemo2");//需要传入oss桶名称、

            int dotPos = multipartFile.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = multipartFile.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            Response res = uploadManager.put(multipartFile.getBytes(), fileName, token);//上传对象
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);//将处理结果转换为JSON
            String key = putRet.key;
//            System.out.println("http://refky7inl.hb-bkt.clouddn.com/" + JSONObject.parseObject(res.bodyString()).get("key"));
//            return "http://refky7inl.hb-bkt.clouddn.com/"+ JSONObject.parseObject(res.bodyString()).get("key");
            System.out.println(key);
            return "http://rhbo22f2u.hb-bkt.clouddn.com/"+key;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}